<template>
  <el-dialog
    :title="title"
    :visible.sync="show"
    :before-close="close"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :width="width + '%'"
     :top="top + 'vh'"
    append-to-body
    class="wp-dialog__panel"
  >
    <div class="wp-order-create">
     <el-collapse v-model="activeNames">
      <el-form
        :model="orderInfo"
        :rules="rules"
        label-position="right"
        label-width="120px"
        ref="orderForm"
      >
       <el-collapse-item title="基本信息" name="1">
        <el-row>
          <el-col :span="12">
            <el-form-item label="客户名称" ref="customerRef" prop="customerCode" :rules="{ required: true, trigger: 'blur', message: '不能为空' }">
              <PopoverSearch  @hide="selectCustomer" :disabled="sourceType!=='default'"  clearable   v-model="orderInfo.customerCode" :name.sync="orderInfo.customerName"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
          <el-form-item label="负责人" prop="chargePerson">
              <Employee-seach :employeeCode.sync="orderInfo.chargePerson" :employeeName.sync="orderInfo.chargePersonName"/>
           </el-form-item>
        </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="下单时间" prop="orderCreateDate">
              <el-date-picker
                style="width:280px"
                v-model="orderInfo.orderCreateDate"
                type="date"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择日期时间"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="交货时间" prop="deliveryDate">
              <el-date-picker
                style="width:280px"
                v-model="orderInfo.deliveryDate"
                type="date"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择日期时间"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <!-- <el-col :span="12">
            <el-form-item label="订单金额" prop="orderAmount">
              <el-input  class="wp-form-280" v-model="orderInfo.orderAmount" placeholder="订单金额"></el-input>
            </el-form-item>
          </el-col> -->
          <el-col :span="12">
            <el-form-item label="备注" prop="remark">
              <el-input
                type="textarea"
                class="wp-form-280"
                rows="2"
                v-model="orderInfo.remark"
                placeholder="备注"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
       </el-collapse-item>
       <el-collapse-item title="收货地址" name="2">
        <el-row>
          <el-col :span="12">
            <el-form-item label="联系人" prop="receiptContactsCode">
            <PopoverSearch
:showMoreBtn="false" ref="contractsRef" @hide="selectContracts"  placeholder="+添加联系人" type='customerSigner' :params="{customerCode:orderInfo.customerCode}"  :disabled="!(orderInfo.customerCode && orderInfo.customerCode!==null)"   v-model="orderInfo.receiptContactsCode" valueKey="contactsCode" lableKey="contactsName"
:name.sync="orderInfo.receiptContactsName"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="地址" prop="receiptAddress">
              <el-input
                class="wp-form-280"
                v-model="orderInfo.receiptAddress"
                placeholder="地址"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="手机号码" prop="receiptContactsMobile">
              <el-input
                class="wp-form-280"
                readonly
                v-model="orderInfo.receiptContactsMobile"
                placeholder="手机号码"
                maxlength="11"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电子邮箱" prop="receiptContactsEmail">
              <el-input
                class="wp-form-280"
                v-model="orderInfo.receiptContactsEmail"
                placeholder="电子邮箱"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="备注" prop="receiptRemark">
              <el-input
                class="wp-form-280"
                type="textarea"
                v-model="orderInfo.receiptRemark"
                placeholder="备注"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
       </el-collapse-item>
        <el-collapse-item title="产品信息" name="3">
            <Product-info  ref="productInfoRef" :orderActualAmount.sync="orderInfo.orderActualAmount" :list.sync="porductList" :updateOption="false" />
         </el-collapse-item>
      </el-form>
     </el-collapse>
    </div>
    <div slot="footer" class="wp-footer__box">
      <el-button @click.native="close">取消</el-button>
      <el-button
        type="warning"
        @click.native="save(1)"
        >保存提交</el-button>
              <el-button
        type="success"
        @click.native="save(0)"
        >保存草稿</el-button>
    </div>
  </el-dialog>
</template>

<script>
import ProductInfo from './detial/productInfo'
import EmployeeSeach from '@/views/components/EmployeeSeach'
import PopoverSearch from '@/views/components/popoverSearch'
import Mixins from './mixins'
export default {
  props: {
    title: String,
    show: {
      type: Boolean,
      default: false
    },
    sourceType: {type: String, default: 'default'},
    customerInfo: {type: Object,
      default: () => {
        return {}
      }},
    top: { type: Number, default: 2 },
    width: { type: Number, default: 80 }
  },
  components: { ProductInfo, EmployeeSeach, PopoverSearch },
  mixins: [Mixins],
  watch: {
    customerInfo: {
      handler (nVal) {
        if (nVal && Object.keys(nVal).length > 0) {
          this.orderInfo.customerCode = nVal.customerCode
          this.orderInfo.customerName = nVal.customerName
        }
      },
      deep: true,
      immediate: true
    }
  },
  data () {
    return {
      orderInfo: {},
      porductList: [],
      activeNames: ['1', '2'],
      rules: {
        chargePerson: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
        orderCreateDate: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
        // orderAmount: [{ required: true, message: '不能为空', trigger: 'blur' }],
        receiptContactsCode: [{ required: true, message: '不能为空', trigger: 'blur' }],
        receiptAddress: [{ required: true, message: '不能为空', trigger: 'blur' }],
        receiptContactsMobile: [{ required: true, message: '不能为空', trigger: 'blur' }]
      }
    }
  },
  methods: {
    close () {
      this.$emit('update:show', false)
    },
    selectCustomer (data) {
      this.$refs.contractsRef.inputClear()
    },
    selectContracts (data) {
      this.$set(this.orderInfo, 'receiptAddress', data.address)
      this.$set(this.orderInfo, 'receiptContactsEmail', data.email)
      this.$set(this.orderInfo, 'receiptContactsMobile', data.mobile)
    },
    /**
     * 保存更新订单信息
     */
    save (status) {
      this.$refs.orderForm.validate((valid) => {
        if (valid && this.checkPorductList(this.porductList)) {
          // let orderActualAmount = 0
          const salesProductList = this.porductList.map(item => {
            const salesProduct = {}
            salesProduct.productCode = item.productCode
            salesProduct.productName = item.productName
            salesProduct.productModel = item.productModel
            salesProduct.productType = item.productType
            salesProduct.productNum = item.productNum
            salesProduct.price = item.price
            salesProduct.unit = item.unit
            salesProduct.discountRate = item.discountRate
            salesProduct.totalAmount = item.totalAmount
            salesProduct.discountTotalAmount = item.discountTotalAmount
            // orderActualAmount += toDecimal(Math.round(salesProduct.discountTotalAmount * 100) / 100)
            return salesProduct
          })

          this.orderInfo.salesOrderDetailInfoList = salesProductList
          this.orderInfo.status = status
          this.orderInfo.orderType = 0
          // this.orderInfo.orderActualAmount = orderActualAmount
          if (status === 1) {
            this.$msgBox.confirm('提交后不可修改', () => {
              this.requestOption('saveSalesOrder', this.orderInfo, (res) => {
                this.close()
                this.$emit('afterSave')
              })
            })
          } else {
            this.requestOption('saveSalesOrder', this.orderInfo, (res) => {
              this.close()
              this.$emit('afterSave')
            })
          }
        }
      })
    },
    checkPorductList (porductList) {
      let validte = true
      if (!porductList || porductList <= 0) {
        this.$msgBox.error('请添加产品')
        if (!this.activeNames.includes('3')) {
          this.activeNames.push('3')
        }
        validte = false
      } else {
        for (let index = 0; index < porductList.length; index++) {
          const product = porductList[index]
          if (!product.productNum) {
            this.$msgBox.error('销售数量不能为空')
            validte = false
            break
          } else if (!product.price) {
            this.$msgBox.error('销售单价不能为空')
            validte = false
            break
          }
        }
      }
      return validte
    }
  }
}
</script>

<style lang="scss" scoped>
.wp-order-create {
  height: 410px;
  overflow: auto;
  padding: 10px;
}
.wp-footer__box {
  text-align: center;
}
.emp-autocomplete {
  li {
    line-height: normal;
    padding: 7px;

    .show-name {
      text-overflow: ellipsis;
      overflow: hidden;
    }
    .highlighted .show-code {
      color: #ddd;
    }
  }
}
</style>
